package com.grep.extra.factory.handle.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.grep.base.cache.TaskAttr;
import com.grep.base.cache.TaskAttrMemory;
import com.grep.base.cache.TaskAttr.ContentParseField;
import com.grep.base.util.FileUtil;
import com.grep.extra.factory.data.IDataQueue;
import com.grep.extra.factory.data.impl.Content;
import com.grep.extra.factory.data.impl.PageContent;
import com.grep.extra.factory.handle.IHandler;
import com.grep.extra.factory.utils.RegexUtil;

public class ContentHandler implements IHandler <PageContent, Content>{

	static Logger logger = LoggerFactory.getLogger(ContentHandler.class);
	
	private IDataQueue<PageContent> task = null ;
	
	private IDataQueue<Content> data = null ;
	
	public IDataQueue getTask() {
		return this.task;
	}

	public void init(IDataQueue<PageContent> task, IDataQueue<Content> data) {
		this.task = task ;
		this.data = data ;
	}

	/**
	 * 从本地html文件中提取相应的内容到 并组织sql 入库
	 */
	public List<Content> process(PageContent k) {
		parseContent(k) ;
		return null;
	}
	/**
	 * 提取关键值
	 * @param pc
	 */
	private void parseContent(PageContent pc){
		String taskId = pc.getTaskId() ;
		String filename = pc.getPath() ;
		String filecontent = null ;
		TaskAttr taskAttr = null ;
		if(filename != null){
			filecontent = FileUtil.readFileByCharset(filename,pc.getCharset());
		}else{
			return ;
		}
		if(filecontent != null && taskId != null){
			taskAttr = TaskAttrMemory.load(taskId);
		}else{
			return;
		}
		if(taskAttr != null){
			Map<String ,ContentParseField> filedMap = taskAttr.getFieldMap() ;
			if(filedMap != null){
				Content content = new Content() ;
				for(String str : filedMap.keySet()){
					ContentParseField field = filedMap.get(str) ;
					String value  = RegexUtil.getValueByRegex(field.getStatrRegex(),
							field.getEndRegex(),filecontent) ;
					content.getValueMap().put(str, value) ;
				}
				content.setSql(taskAttr.getSql());
				this.data.put(content) ;
				
				logger.info("[-- path:{},insert sql is :]{}",pc.getPath(),content.getSql()) ;
			}
		}
	}
}
